package com.santoker.user.service.service.biz.file.impl;

import com.santoker.baseservice.ApiResponseCode;
import com.santoker.user.service.config.ConfigProperty;
import com.santoker.user.service.dto.vo.file.FileInfoVo;
import com.santoker.user.service.exception.CommonServiceException;
import com.santoker.user.service.service.biz.file.FileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Autowired
    private ConfigProperty configProperty;

    final private String MENTOR_DEFAULT_PATH = "/default/mentor.jpeg";

    public FileInfoVo upload(MultipartFile file, String account) {
        FileInfoVo fileInfoVo = new FileInfoVo();

        // 获取文件名
        String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();

        String uploadPath = generateUploadPath(fileName, account);
        doUpload(uploadPath, file);

        fileInfoVo.setUrl(generateFileDisplayUrl(fileName, account));
        fileInfoVo.setName(fileName);

        return fileInfoVo;
    }

    public void doUpload(String path, MultipartFile file) {
        log.info("upload file.... fileName: {}, path: {}", file.getName(), path);
        File uploadFile = new File(path);
        try {
            //存储文件
            file.transferTo(uploadFile);
            uploadFile.setReadable(true, false);
            uploadFile.setExecutable(true, false);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            throw new CommonServiceException(ApiResponseCode.SYSTEM_ERROR.getCode(), "文件存储失败");
        }
    }

    public String generateUploadPath(String fileName, String account) {
        StringBuilder userDirPath = new StringBuilder();

        userDirPath.append(configProperty.fileUploadPath)
                .append("/")
                .append(account)
                .append("/");

        // if user directory does not exist, make
        File userDir = new File(userDirPath.toString());
        if (!userDir.exists() && !userDir.isDirectory()) {
            userDir.mkdir();
            userDir.setExecutable(true, false);
            userDir.setReadable(true, false);
        } else if (userDir.exists() && !userDir.isDirectory()) {
            log.error("{} is not a url!", userDirPath.toString());
            throw new CommonServiceException(ApiResponseCode.SYSTEM_ERROR.getCode(), "文件路径生成失败");
        }

        userDirPath.append(fileName);

        return userDirPath.toString();
    }

    public String generateFileDisplayUrl(String fileName, String account) {
        StringBuilder userDirPath = new StringBuilder();
        userDirPath.append(configProperty.fileDomain)
                .append("/").append(configProperty.fileDisplayPath)
                .append("/").append(account).append("/");
        userDirPath.append(fileName);

        return userDirPath.toString();
    }

    public String getMentorDefaultUrl() {
        StringBuilder builder = new StringBuilder();
        builder.append(configProperty.fileDomain)
                .append("/").append(configProperty.fileDisplayPath)
                .append(MENTOR_DEFAULT_PATH);
        return builder.toString();
    }

    private String getFileName(String url) {
        Pattern pattern = Pattern.compile("\\/(\\w+)\\/(\\w+)$");
        Matcher matcher = pattern.matcher(url);

        if (matcher.find()) {
            return matcher.group(0);
        } else {
            return null;
        }
    }

}
